document.addEventListener("DOMContentLoaded", function() {
    var btnUserInfo = document.getElementById('btnUserInfo');
    var btnOrdersInfo = document.getElementById('btnOrdersInfo');
    var messageElement = document.getElementById("message");

    function getUserIDFromMessage() {
        const messageText = messageElement.textContent;
        const match = messageText.match(/用户ID：(\d+)/);
        return match ? parseInt(match[1], 10) : null;
    }

    btnUserInfo.addEventListener('click', function() {
        const userId = getUserIDFromMessage();
        if (userId) {
            window.location.href = `/Personcenter/user-info.html?userId=${userId}`;
        } else {
            messageElement.textContent = "请先登录。";
        }
    });

    btnOrdersInfo.addEventListener('click', function() {
        const userId = getUserIDFromMessage();
        if (userId) {
            window.location.href = `/Personcenter/orders-info.html?userId=${userId}`;
        } else {
            messageElement.textContent = "请先登录。";
        }
    });

    // 初始加载用户ID
    fetchUserId();

    function fetchUserId() {
        fetch('/api/get-user-id', {
            credentials: 'include'
        }).then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch user ID');
            }
            return response.text();
        }).then(userId => {
            if (userId === "not_logged_in") {
                document.getElementById("message").textContent = "您还未登录，请先登录。";
            } else {
                document.getElementById("message").textContent = `欢迎回来，用户ID：${userId}`;
            }
        }).catch(error => {
            console.error('Error:', error);
            document.getElementById("message").textContent = "登录状态获取失败，请刷新页面或重新登录。";
        });
    }
});

function refreshIframes() {
    const iframes = document.querySelectorAll('iframe');
    iframes.forEach(iframe => {
        iframe.src = 'about:blank'; // 清空iframe内容
    });
}

function clearBrowserStorage() {
    // 清除cookies
    document.cookie.split(";").forEach(function(c) {
        document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/;domain=" + window.location.hostname);
    });
    // 清除localStorage
    localStorage.clear();
    // 清除sessionStorage
    sessionStorage.clear();
}